var app = getApp();
Page({
  data: {
    packageInfo: {},
	categories: [],
	allItems: [], // 所有项目（含选中状态）
	requiredItems: [], // 必选项目
	optionalItems: [], // 可选项目
	selectedOptionalItems: [], // 已选中的可选项目
	currentCategory: '',
	currentItems: [], // 当前分类项目
	selectedItems: [], // 选中的项目列表
	totalOriginalPrice: 0, // 原价总和
	totalDiscount: 0, // 总折扣
	totalFinalPrice: 0 // 最终价格
  },

  onLoad(options) {
    if (options.packageId) {
      this.loadPackageDetail(options.packageId);
    } else {
      wx.navigateBack();
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
    }
  },

  // 加载套餐详情
  loadPackageDetail(packageId) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟接口请求
    app.util.request({
      url: `Physical/detail`,
	  data: {
		  id: packageId
	  },
      success: (res) => {
        if (res.data.code === 1) {
          const packageInfo = res.data.data.package;
		  wx.setStorageSync('packageInfo',packageInfo)
          const items = res.data.data.itemdata;
          
          // 提取分类
          const categories = [...new Set(items.map(item => ({
            id: item.category_id,
            name: item.category_name
          })))];
          
          // 计算总项目数
          const totalItems = items.length;
          
          // 默认显示第一个分类
          const currentCategory = categories.length > 0 ? categories[0].id : '';
          const currentItems = items.filter(item => item.category_id === currentCategory);
          
		  const requiredItems = items.filter(item => item.item_type === 1);
		  const optionalItems = items.filter(item => item.item_type !== 1);
		  const selectedOptionalItems = optionalItems.filter(item => item.checked);
		  // 计算价格
		  this.setData({
			  packageInfo
		  })
		  const { totalOriginal, totalDiscount, totalFinal } = this.calculatePrices(requiredItems, selectedOptionalItems);
		  console.log(totalFinal)
		  console.log(totalDiscount)
          this.setData({
			  allItems: items,
			  requiredItems,
			  optionalItems,
			  selectedOptionalItems,
			  totalOriginalPrice: totalOriginal,
			  totalDiscount: totalDiscount,
			  totalFinalPrice: totalFinal
          });
        } else {
          wx.showToast({
            title: '获取详情失败',
            icon: 'none'
          });
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  addFloatsAndRound(a, b) {
    // 放大倍数（1e10 足够处理大部分场景，避免精度丢失）
    const factor = 1e10;
    // 转换为整数相加，再转回浮点数，得到准确的和
    const sum = (Math.round(a * factor) + Math.round(b * factor)) / factor;
    // 四舍五入保留两位小数（返回数字）
    return Math.round(sum * 100) / 100;
  },
  addFloatsAndRoundfour(a, b,c,d) {
    // 放大倍数（1e10 足够处理大部分场景，避免精度丢失）
    const factor = 1e10;
    // 转换为整数相加，再转回浮点数，得到准确的和
    const sum = (Math.round(a * factor) + Math.round(b * factor)-Math.round(c * factor) - Math.round(d * factor)) / factor;
    // 四舍五入保留两位小数（返回数字）
    return Math.round(sum * 100) / 100;
  },
// 计算价格
  calculatePrices(requiredItems, optionalItems) {
    // 计算必选项目价格
    const requiredTotal = requiredItems.reduce((sum, item) => {
      sum.original = this.addFloatsAndRound(sum.original,item.price);
      sum.discount = this.addFloatsAndRound(sum.discount,item.item_discount);
      return sum;
    }, { original: 0, discount: 0 });
	if(this.data.packageInfo.cate_id != 'auto'){
		requiredTotal.original = this.data.packageInfo.total_original_price
		requiredTotal.discount = this.data.packageInfo.total_original_price-this.data.packageInfo.final_price
	}
    // 计算可选项目价格
    const optionalTotal = optionalItems.reduce((sum, item) => {
	  sum.original = this.addFloatsAndRound(sum.original,item.price);
	  sum.discount = this.addFloatsAndRound(sum.discount,item.item_discount);
      return sum;
    }, { original: 0, discount: 0 });
    // 总计
    return {
      totalOriginal: this.addFloatsAndRound(requiredTotal.original,optionalTotal.original).toFixed(2),
      totalDiscount: this.addFloatsAndRound(requiredTotal.discount,optionalTotal.discount).toFixed(2),
      totalFinal: this.addFloatsAndRoundfour(requiredTotal.original,optionalTotal.original,requiredTotal.discount,optionalTotal.discount).toFixed(2)
    };
  },
  makePhoneCall(e){
          wx.makePhoneCall({
                  phoneNumber: e.currentTarget.dataset.tel
          });
      },
  calculatePricesall(optionalItems) {  	 
	//套餐内价格
	if(this.data.packageInfo.cate_id == 'multi'){
		let original = this.data.packageInfo.total_original_price
		let discount = this.data.packageInfo.total_original_price-this.data.packageInfo.final_price
	}else{
		let original = 0;
		let discount = 0;
	}	
    // 计算可选项目价格
    const optionalTotal = optionalItems.reduce((sum, item) => {
  	  sum.original = this.addFloatsAndRound(sum.original,item.price);
  	  sum.discount = this.addFloatsAndRound(sum.discount,item.item_discount);
      return sum;
    }, { original: 0, discount: 0 });
    // 总计
    return {
      totalOriginal: optionalTotal.original.toFixed(2),
      totalDiscount: optionalTotal.discount.toFixed(2),
      totalFinal: this.addFloatsAndRoundfour(original,optionalTotal.original,discount,optionalTotal.discount).toFixed(2)
    };
  },
  // 可选项目选择变化
    onOptionalChange(e) {
      const itemId = e.currentTarget.dataset.id;
	  // 更新可选项目状态
      const optionalItems = this.data.optionalItems.map(item => {
          if (item.id === itemId) {
            return { ...item, checked: !item.checked }; // 关键：手动取反状态
          }
          return item;
        });
  
      // 2. 更新已选可选项目列表
        const selectedOptionalItems = optionalItems.filter(item => item.checked);
        
        // 3. 重新计算价格（和原来逻辑一致）
        const { totalOriginal, totalDiscount, totalFinal } = this.calculatePrices(
          this.data.requiredItems,
          selectedOptionalItems
        );
  
      this.setData({
        optionalItems,
        selectedOptionalItems,
        totalOriginalPrice: totalOriginal,
        totalDiscount: totalDiscount,
        totalFinalPrice: totalFinal
      });
    },
onItemCheck(e) {
    const itemId = e.currentTarget.dataset.id;
    const checked = e.detail.value.length > 0;
    
    // 更新所有项目中的状态
    const allItems = this.data.allItems.map(item => {
      if (item.id === itemId) {
        return { ...item, checked };
      }
      return item;
    });

    // 更新当前分类项目的状态
    const currentItems = this.data.currentItems.map(item => {
      if (item.id === itemId) {
        return { ...item, checked };
      }
      return item;
    });

    // 更新选中列表和价格
    const selectedItems = allItems.filter(item => item.checked);
    const { totalOriginal, totalDiscount, totalFinal } = this.calculatePricesall(selectedItems);
	console.log("totalOriginal:",totalOriginal);
	console.log("totalDiscount:",totalDiscount);
	console.log("totalFinal:",totalFinal);
    this.setData({
      allItems,
      currentItems,
      selectedItems,
      totalOriginalPrice: totalOriginal,
      totalDiscount: totalDiscount,
      totalFinalPrice: totalFinal
    });
  },

  // 取消选中项目（仅非必选）
  cancelItem(e) {
    const itemId = e.currentTarget.dataset.id;
    
    // 找到项目并取消选中
    const allItems = this.data.allItems.map(item => {
      if (item.id === itemId && !item.required) { // 仅非必选可取消
        return { ...item, checked: false };
      }
      return item;
    });

    // 更新当前分类项目
    const currentItems = this.data.currentItems.map(item => {
      if (item.id === itemId && !item.required) {
        return { ...item, checked: false };
      }
      return item;
    });

    // 更新选中列表和价格
    const selectedItems = allItems.filter(item => item.checked);
    const { totalOriginal, totalDiscount, totalFinal } = this.calculatePricesall(selectedItems);

    this.setData({
      allItems,
      currentItems,
      selectedItems,
      totalOriginalPrice: totalOriginal,
      totalDiscount: totalDiscount,
      totalFinalPrice: totalFinal
    });
  },

  // 前往预约页面
  goToAppointment() {
    // 收集选中的项目IDgoToAppointment
        const selectedItemIds = [
          ...this.data.requiredItems.map(item => item.id),
          ...this.data.selectedOptionalItems.map(item => item.id)
        ].join(',');
    
        wx.navigateTo({
          url: `/vp_pz/pages/physicalExam/appointment/appointment?packageId=${this.data.packageInfo.id}&selectedItems=${selectedItemIds}&price=${this.data.totalFinalPrice}`
        });
  }
});